#include<iostream>
#include<string>
#include<unistd.h>
void cutString(const std::string&target,std::string&str1,std::string&str2,const std::string&sep )
{
   size_t pos= target.find(sep);
   if(pos!=std::string::npos)
   {
       str1= target.substr(0,pos);
       str2=target.substr(pos+sep.size());
   }
}
//通过method来获取参数的方法
bool getQueryString(std::string&query)
{
        std::string method;
   method=getenv("METHOD");
  if("GET"==method)
  {
    std::cerr<<"into Get"<<std::endl;
         //从环境变量获取参数
   query=getenv("QUERY_STRING");
    std::cerr<<query<<std::endl;
     return true;

     
  }
  if("POST"==method)
  {
    std::cerr<<"DEBUG: into POST "<<std::endl;

           //POST方法参数通过管道传
           if(getenv("CONTENT_LENGTH")==NULL)
           {
            std::cerr<<"NULL Ptr"<<std::endl;
           }
      int len=atoi(getenv("CONTENT_LENGTH"));
      std::cerr<<"DEBUG:"<<len<<std::endl;
      char ch;
      while(len)
      {
       ssize_t n= read(0,&ch,1);
       if (n>0)
       {
        query.push_back(ch);
        len--;
       }
       
      }
      std::cerr<<"DEBUG:"<<"Read finish!"<<std::endl;
      return true;
  }
  return false;
}
//通过对两个值的运算得到一个返回的字符串
void Calculator(int a,int b,std::string&ret)
{
  int add=a+b;
  int sub=a-b;
  int div=0;
  if(b!=0)
  {
  div=a/b;
  }
  int mul=a*b;
  ret="a+b="+std::to_string(add);
  ret+="\n";
  ret+="a-b="+std::to_string(sub);
  ret+="\n";
  ret+="a/b="+std::to_string(div);
  ret+="\n";
  ret+="a*b="+std::to_string(mul);
  ret+="\n";
}
//通过解析参数得到两个值
void parsingParameters(int&a,int&b,const std::string&query)
{
  //对参数进行解析得到a b 两数的值
       std::string str1;
       std::string str2;
       cutString(query,str1,str2,"&"); //a=100&b=200 -> a=100, b=200
      // std::cerr<<str1<<" "<<str2<<std::endl;
       std::string variable1;
       std::string variable2;
       std::string value1;
       std::string value2;
       cutString(str1,variable1,value1,"=");
       cutString(str2,variable2,value2,"=");
      // std::cerr<<variable1<<" "<<value1<<std::endl;
      // std::cerr<<variable2<<" "<<value2<<std::endl;

       a=atoi(value1.c_str());
       b=atoi(value2.c_str());
}
int main()
{
    std::cerr<<"i am a cgi progress!!\n";
    //std::cerr<<getenv("PWD");
    //1.从环境变量中获取请求的method


   // std::cerr<<getenv("METHOD")<<std::endl;

  //   if("GET"==method)
  //   {
  //   std::cerr<<getenv("QUERY_STRING")<<std::endl;
  //   }
  //  else if("POST"==method)
  //  {
  //   std::cerr<<"Content_length: "<<getenv("CONTENT_LENGTH")<<std::endl;
  //  }
   //2. 通过method判断从管道读参数还是从环境变量读
   std::string query_string;
  if( getQueryString(query_string))
  {
       //解析字符串得到两个
       int a,b;
       parsingParameters(a,b,query_string);

       //对a b进行加减乘除运算,得到一个可返回的字符串
       std::string ret;
        Calculator(a,b,ret);
        std::cout<<ret;//已重定向到管道的写端
  }

   
    return 0;
}